package com.yehun.web.interceptor;


import com.yehun.enums.ResultEnum;
import com.yehun.utils.Constant;
import com.yehun.utils.JsonUtils;
import com.yehun.utils.PropertyUtils;
import com.yehun.model.RestfulModel;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 限制请求方式
 * Created by Genius on 2017/4/25 0025.
 */
public class RequestLimitInteceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Boolean envirinment = PropertyUtils.getConfig("environment", Boolean.class);
        if (envirinment && !Objects.equals(request.getMethod().toUpperCase(), "POST")) { // 只允许post请求
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            response.getWriter().println(JsonUtils.serialize(new RestfulModel(ResultEnum.Fail, "请使用post请求!")));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}